import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;

public class trainBuyTicket {
   public volatile Object ticket=5;
   private ArrayBlockingQueue arrayBlockingQueue=new ArrayBlockingQueue(10);
    public static void main(String[] args) throws InterruptedException {
        trainBuyTicket trainBuyTicket=new trainBuyTicket();
        trainBuyTicket.buyTicket();
    }

    public  void buyTicket() throws InterruptedException {
        ReentrantLock lock =new ReentrantLock();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        Thread trainThread=new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){//TODO 这里需要主线程去终止放票线程
                    //每三秒去设置
                    try {
                        Thread.sleep(3000L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (int i = 0; i < 5; i++) {
                        arrayBlockingQueue.add("1");
                    }
                    System.out.println("开始放票："+arrayBlockingQueue.size());

                }
            }
        });
        trainThread.start();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        arrayBlockingQueue.take();
                        countDownLatch.countDown();
                        System.out.println(Thread.currentThread().getName()+":抢票成功");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        //等待所有的线程都执行完
        countDownLatch.await();
        System.out.println("done");
        System.exit(0);
        //for (int i = 0; i < 10; i++) {
        //    Thread t=new Thread(new Runnable() {
        //        @Override
        //        public void run() {
        //            //锁住自己去买票
        //            lock.lock();
        //            try {
        //                while (ticket<=0){
        //                    //如果票量为0,则乘客需要取等待
        //                    System.out.println(Thread.currentThread().getName()+":开始等待");
        //                    cu.await();
        //                }
        //                ticket--;
        //                countDownLatch.countDown();
        //                System.out.println(Thread.currentThread().getName()+":买票成功");
        //            }catch (Exception e){
        //
        //            }finally {
        //                lock.unlock();
        //            }
        //        }
        //    });
        //    t.start();
        //}

    }
}
